#include <async_server.h>

AsyncServer::AsyncServer(boost::asio::io_context& ioct):ioct_(ioct)
{
	boost::asio::ip::tcp::endpoint serverPoint(boost::asio::ip::address::from_string("127.0.0.1"), 12345);
	this->accptor_ = std::make_shared<boost::asio::ip::tcp::acceptor>(ioct_,serverPoint);
}

void AsyncServer::startAccept()
{
	// 创建session的io_context后面需要从io_context服务池中获取
	std::shared_ptr<Session> session = std::make_shared<Session>(ioct_, this);
	this->accptor_->async_accept(session->socket_,
		boost::bind(&AsyncServer::acceptHandler, this, session, boost::placeholders::_1));
}

bool AsyncServer::clearSession(std::string sessionId)
{
	if (sessionMap_.find(sessionId) != sessionMap_.end()) {
		sessionMap_.erase(sessionId);
		return true;
	}
	return false;
}

void AsyncServer::start()
{
	startAccept();
}

void AsyncServer::acceptHandler(std::shared_ptr<Session> session, const boost::system::error_code& error)
{
	if (!error) {
		this->sessionMap_.insert(std::make_pair(session->getId(), session));
		std::cout << "connection from: " << session->socket_.remote_endpoint().address().to_string() << ":" << session->socket_.remote_endpoint().port() << std::endl;
		session->startRead();
		startAccept();
	}
	else {
		std::cerr << error.what() << std::endl;
	}
}
